package crp.services.api.graphql;

import crp.core.security.app.AuthService;
import crp.services.api.graphql.models.AccessTokenPayload;
import crp.services.api.graphql.models.BasicIdentityInput;
import crp.services.api.graphql.models.SSOIdentityInput;
import org.eclipse.microprofile.graphql.GraphQLApi;
import org.eclipse.microprofile.graphql.Mutation;

import javax.annotation.security.PermitAll;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

@GraphQLApi
@RequestScoped
@Transactional
public class IdentityGraphQLApi {
    private final AuthService authService;

    @Inject
    public IdentityGraphQLApi(AuthService authService) {
        this.authService = authService;
    }

    @Mutation
    @PermitAll
    @NotNull
    public AccessTokenPayload basicLogin(@NotNull @Valid BasicIdentityInput input) {
        return AccessTokenPayload.of(authService.basic()
                .authenticate(input.getUsername(), input.getPassword()));
    }

    @Mutation
    @PermitAll
    @NotNull
    public AccessTokenPayload ssoLogin(@NotNull @Valid SSOIdentityInput input) {
        return AccessTokenPayload.of(authService.sso()
                .authenticate(input.getProvider(), input.ofAttributes()));
    }
}
